package com.newly.center.sys.service.tenant.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newly.common.base.constants.CommonConstant;
import com.newly.common.base.entity.sys.tenant.dto.TenantDto;
import com.newly.common.base.entity.sys.tenant.po.TenantPo;
import com.newly.common.mapper.sys.TenantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.List;

/**
 * @program: newly-parent
 * @remark: 租户业务基类
 * @author: guan
 * @create: 2021-11-17 11:28
 */
public class AbstractTenantService extends ServiceImpl<TenantMapper, TenantPo> {

    @Autowired
    protected TenantMapper tenantMapper;

    @Autowired
    protected PasswordEncoder passwordEncoder;

    protected Long insert(TenantDto tenantDto) {
        TenantPo tenantPo = BeanUtil.copyProperties(tenantDto, TenantPo.class);
        // 密码加密
        tenantPo.setPassword(passwordEncoder.encode(tenantPo.getPassword()));
        DateTime date = DateUtil.date();
        tenantPo.setCreateTime(date);
        tenantPo.setUpdateTime(date);
        int result = tenantMapper.insert(tenantPo);
        if (result > 0) {
            return tenantPo.getId();
        }
        return null;
    }

    protected List<TenantPo> selectByIds(List<Long> tenantIds) {
        return tenantMapper.selectBatchIds(tenantIds);
    }

    protected TenantPo selectByUsernameAndType(String username, int type) {
        if (StrUtil.isBlank(username) || ObjectUtil.isEmpty(type))
            return null;
        LambdaQueryWrapper<TenantPo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TenantPo::getUsername, username);
        wrapper.eq(TenantPo::getDel, CommonConstant.DeleteFlag.NO_DELETE.getCode());
        //wrapper.eq(TenantPo::getStatus, CommonConstant.DeleteFlag.NO_DELETE.getCode());
        //wrapper.eq(TenantPo::getType, type);
        return tenantMapper.selectOne(wrapper);
    }
}
